package com.jnshu.filter;

import com.jnshu.constant.Constant;
import com.jnshu.service.AdminService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author pipiretrak
 * @date 2019/8/3 - 11:31
 */
@Component
@Slf4j
public class LoginFilter extends ZuulFilter {

    @Autowired(required = false)
    AdminService adminService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        String name = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RequestContext currentContext = RequestContext.getCurrentContext();
        log.info("取出来的名字："+name);
        if (name == null){
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            try {
                HttpServletResponse response = currentContext.getResponse();
                response.setContentType("text/html;charset=utf-8");
                currentContext.getResponse().getWriter().write("没有后台账户");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        Long id = adminService.selectManageIdByName(name);
        log.info("取出来的ID："+id);
        if (id == null || id == 0){
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            try {
                currentContext.getResponse().getWriter().write("没有后台ID");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        try {
            currentContext.addZuulRequestHeader(Constant.LOGINNAME, URLEncoder.encode(name,"UTF-8"));
            currentContext.addZuulRequestHeader(Constant.LOGINID,URLEncoder.encode(String.valueOf(id),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
